#!/bin/bash

function usage()
{
    echo "Usage:"
    echo "    collect_nvme.sh [-f file/-n nodes]"
    echo "      -f [file_name]"
    echo "      -n [node_list]"
    echo "Example:"
    echo "    collect_nvme.sh -f /root/nodes.txt"
    echo "    collect_nvme.sh -n testr01n01,testr01n02"
}

if [[ "x$1" == "x-h" ]] || [[ "x$1" == "x--help" ]]; then
    usage
    exit 1
fi

if [[ $# != 2 ]]; then
    usage
    exit 1
fi

if [[ "x$1" == "x-f" ]]; then
    if [ ! -f $2 ]; then
        echo "cannot access '$2': No such file or directory"
        exit 1
    fi
    nodes=($(cat $2|tr '\n' ' '))
elif [[ "x$1" == "x-n" ]]; then
    nodes=($(echo $2|tr ',' ' '))
else
    usage
    exit 1
fi

collect_date=$(date +%Y%m%d-%H%M%S)
shell_pwd=$(cd "$( dirname "$0" )" && pwd)
if [ ! -d "${shell_pwd}/logs" ];
then
  mkdir ${shell_pwd}/logs
fi

GREEN="\E[1;32m"
RES="\E[0m"
output_file="${shell_pwd}/logs/collect_nvme_${collect_date}.csv"

echo "Starting collect nodes nvme info."
nodes_str=$(IFS=, ; echo "${nodes[*]}")
echo "------------------------------------------------"
echo -e "TARGET NODES:\n    ${nodes_str}"
echo "------------------------------------------------"
echo "hyper_node_id,nvme_info" >${output_file}

for node in ${nodes[@]}; do
    nvme_info=$(ssh -Tq -o ConnectTimeout=3 -o ConnectionAttempts=1 $node "if which nvmemgr &>/dev/null;then nvmemgr list; elif which nvme &>/dev/null;then nvme list; else echo 'nvmemgr/nvme command not found';fi")
    echo "${node},\"${nvme_info}\"" >>${output_file}
done

echo "The job of collect is done. You can view it the link below."
echo -e "Output File: ${GREEN}${output_file}${RES}"
exit 0

